<template>


<el-collapse>
	<el-collapse-item name="0">
		<template #title>
			<el-text type="primary" size="large">导出表格选择</el-text>
		</template>

		<el-table :data="export_list" style="width: 100%">
			<el-table-column prop="id" label="编号" v-if="false"/>

			<el-table-column prop="name" label="表格名称"/>

			<el-table-column align="right">
				<template #header>
					<!-- 把按钮大小调小，否则一排放不下 -->
					<el-button @click="handleAdd()">添加表格</el-button>
					<el-button @click="refresh()">搜索</el-button>
				</template>

				<template #default="scope">
					<el-button @click="show_content_list(scope.$index, scope.row)">查看内容</el-button>
					<el-button @click="handleEdit(scope.row)">修改</el-button>
					<el-button @click="return_select_table_id(scope.row)">选定表格</el-button>
					<el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

	</el-collapse-item>

	<el-collapse-item name="1">
		<template #title>
			<el-text type="primary" size="large">设置导出表格 当前表格：{{area4.area2_name}}</el-text>
		</template>
		<el-row :gutter="20">

			<!-- 备选列表 -->
			<el-col :span="12">
				<!-- 最终显示列表 -->
				<el-table :data="content_list" style="width: 100%">
					<el-table-column prop="id" label="编号" v-if="false"/>
					<el-table-column prop="no" label="编号"/>
					<el-table-column prop="big_name" label="大类名称"/>
					<el-table-column prop="small_name" label="小类名称"/>

					<el-table-column align="right" width="100px">
						<template #header>
							<!-- 空置 -->
						</template>
						<template #default="scope">
							<el-button type="danger" @click="delete_selected_small_id(scope.row)">删除</el-button>
						</template>
					</el-table-column>

				</el-table>
			</el-col>


			<el-col :span="12">
				<!--		在这里进行预选-->

				<el-form :inline="true">

				<el-form-item label="大类搜索">
					<FuzzySearchBigVer2 @DataUse="big_auto_complete_in_exportDIY($event as any)" ref="big_clear" :disable="false"/>
				</el-form-item>

				<el-form-item label="小类搜索">
					<FuzzySearchSmallVer2 @DataUse="small_auto_complete_in_exportDIY($event as any)" ref="small_clear" :disable="false"/>
				</el-form-item>

				<el-form-item prop="use" label="启用状态">
					<el-radio-group v-model="fuzzy_search.use">
						<el-radio-button label="启用">启用</el-radio-button>
						<el-radio-button label="未启用">未启用</el-radio-button>
						<el-radio-button label="全部">全部</el-radio-button>
					</el-radio-group>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="return_small_list()">返回数据</el-button>
					<el-button type="primary" @click="clear_small_list()">清空表格</el-button>
				</el-form-item>

				</el-form>


				<el-table :data="optional_list" style="width: 100%">
					<el-table-column prop="id" label="编号" v-if="false"/>
					<el-table-column prop="no" label="编号"/>
					<el-table-column prop="big_name" label="大类名称"/>
					<el-table-column prop="small_name" label="小类名称"/>
					<el-table-column prop="units" label="单位"/>
					<el-table-column prop="number" label="数量"/>

					<el-table-column align="right" width="80px">
						<template #header>
							<!-- 空置 -->
						</template>
						<template #default="scope">
							<el-button @click="add_new_small_id(scope.row)">添加</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- 分页 -->
				<el-pagination
					small
					v-model:current-page="currentPage"
					v-model:page-size="pageSize"
					:page-sizes="[100, 200, 500]"
					:disabled="disabled"
					:background="background"
					layout="total, sizes, prev, pager, next, jumper"
					:total=" total "
				/>
			</el-col>


		</el-row>

	</el-collapse-item>

	<el-collapse-item name="2">
		<template #title>
			<el-text type="primary" size="large">表格显示部分</el-text>
		</template>
		<el-form :inline="true">

			<el-form-item label="当前表格">
				<el-input v-model="area4.name" disabled/>
			</el-form-item>

			<el-form-item label="出入库">
				<el-radio-group v-model="area4.trend">
					<el-radio-button :label="false">入库</el-radio-button>
					<el-radio-button :label="true">出库</el-radio-button>
				</el-radio-group>
			</el-form-item>

			<el-form-item label="日期范围">
				<el-date-picker
					v-model="area4.date_range"
					type="daterange"
					range-separator="-"
					start-placeholder="Start date"
					end-placeholder="End date"
					value-format="YYYY-MM-DD"
				/>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="return_table()">搜索</el-button>
				<el-button type="primary" @click="select_table4_col()">选择导出列</el-button>
<!--				<el-button type="primary" @click="make_table4_at_web()">导出表格（前端）</el-button>-->
				<el-button type="primary" @click="return_small_list_backhand()">导出表格（后端）</el-button>
			</el-form-item>

		</el-form>
		<!-- 显示导出的表格 -->
		<el-table :data="DIY_data" id="table4">
			<el-table-column prop="actual_date_str" label="日期" v-if="table1_head_optional.actual_date_str"/>
			<el-table-column prop="no" label="编号" v-if="table1_head_optional.no"/>
			<el-table-column prop="big_name" label="大类名称" v-if="table1_head_optional.big_name"/>
			<el-table-column prop="small_name" label="小类名称" v-if="table1_head_optional.small_name"/>
			<el-table-column prop="model" label="型号" v-if="table1_head_optional.model"/>
			<el-table-column prop="handle_name" label="处理方" v-if="table1_head_optional.handle_name"/>
			<el-table-column prop="units" label="单位" v-if="table1_head_optional.units"/>
			<el-table-column prop="change_abs" label="数量" v-if="table1_head_optional.change"/>
			<el-table-column prop="unit_price" label="单价" v-if="table1_head_optional.unit_price"/>
			<el-table-column prop="total_abs" label="总价" v-if="table1_head_optional.total"/>
			<el-table-column prop="remarks" label="备注" v-if="table1_head_optional.remarks"/>
		</el-table>

	</el-collapse-item>
</el-collapse>


<el-dialog
	v-model="table1_head_show_visible"
	title="表头选项"
	:close-on-click-modal='false'
	:close-on-press-escape='false'
	:show-close='false'
>
	<el-checkbox v-model="table1_head_optional.big_name" label="大类名称"/>
	<el-checkbox v-model="table1_head_optional.small_name" label="小类名称"/>
	<el-checkbox v-model="table1_head_optional.no" label="编号"/>
	<el-checkbox v-model="table1_head_optional.actual_date_str" label="日期"/>
	<el-checkbox v-model="table1_head_optional.handle_name" label="处理方"/>
	<el-checkbox v-model="table1_head_optional.units" label="单位"/>
	<el-checkbox v-model="table1_head_optional.change" label="数量"/>
	<el-checkbox v-model="table1_head_optional.unit_price" label="单价"/>
	<el-checkbox v-model="table1_head_optional.total" label="总价"/>
	<el-checkbox v-model="table1_head_optional.remarks" label="备注"/>
	<template #footer>
      <span class="dialog-footer">
        <el-button @click="select_table4_col_confirm()">确定</el-button>
      </span>
	</template>
</el-dialog>


<!-- 添加 / 修改角色的添加框 -->
<el-dialog v-model="dialogFormVisible" :title=" add_revise " label-width="70px">
	<el-form :model="formInline" :rules="rules" ref="form">

		<el-form-item prop="name" label="表格名称">
			<el-input v-model="formInline.name" autocomplete="off"/>
		</el-form-item>


	</el-form>
	<template #footer>
      <span class="dialog-footer">
				<!-- form?.resetFields() 关闭表单之后重置校验结果 -->
        <el-button @click="dialogFormVisible = false; form?.resetFields()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">
          保存
        </el-button>
      </span>
	</template>
</el-dialog>
</template>

<script lang="ts">
export default {
	name: "PersonnelManagement"
}
</script>
<script lang="ts" setup>
import {reactive, ref, watch} from 'vue'
// import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox, ElTable} from "element-plus";
// import {useStore} from '@/pinia'
import type {FormInstance, FormRules} from 'element-plus'
// import {Router} from "vue-router";
import {
	DIYContent,
	DIYFileCRUDResponseData,
	DIYFileDate,
	DIYReturnDataResponseData
} from "@/api/first/ExportFile/type.ts";
import {req04Table, reqDIYCRUD, reqDIYTable} from "@/api/first/ExportFile/index.ts";
import type {SmallAutoCompletion} from "@/components/first/FuzzySearchSmallVer2.vue";
import type {BigAutoCompletion} from "@/components/first/FuzzySearchBigVer2.vue";
import {reqSmallList} from "@/api/first/PartsManagement";
import {SmallInfo, SmallTableCRUDResponse} from "@/api/first/PartsManagement/type.ts";
import FuzzySearchBigVer2 from "@/components/first/FuzzySearchBigVer2.vue";
import FuzzySearchSmallVer2 from "@/components/first/FuzzySearchSmallVer2.vue";
// import {make_excel_file} from "@/hooks/make_excel_file.ts";
// const router: Router = useRouter()
// const store = useStore()
// const make_table4_at_web = () => {
// 	make_excel_file('自定义表格', area4.name)
// }
//---------------------------------------------------------------
// 表格3 候选内容提出表 optional_list
//---------------------------------------------------------------
const optional_list = ref<SmallInfo[]>([])
const big_clear = ref()
const small_clear = ref()
const background = ref<boolean>(true)  // 是否带背景方框
const disabled = ref<boolean>(false)  // 是否可用
const currentPage = ref<number>(1)  // 当前所在页数
const pageSize = ref<number>(100)  // 一页有几条记录
const total = ref<number>(0) // 总条数
watch([currentPage, pageSize], () => {
	// 无需对表单进行验证，因为要回传的东西不可能有错
	read_small()
})
const fuzzy_search = reactive<{
	target: string
	mode: 'big' | 'small'
	id: number | ''
	use: '启用' | '未启用' | '全部'
}>({
	target: '',
	mode: 'big',
	id: '',
	use: '启用',
})
// 清空小类数据
const clear_small_list = () => {
	optional_list.value = []
}
// 返回小类数据
const return_small_list = () => {
	if (now_export_table_index.value === undefined) {
		ElMessage.warning('请选择需要导出的表格')
		return
	}
	read_small()
}

const read_small = () => {
	reqSmallList({
		mode: 'read',
		read: {
			mode: fuzzy_search.mode,
			id: fuzzy_search.id as number,
			use: fuzzy_search.use,
			start: (currentPage.value - 1) * pageSize.value,
			stop: currentPage.value * pageSize.value,
		}
	}).then((res: SmallTableCRUDResponse) => {
		optional_list.value = res.read?.small_list as any
		total.value = res.read?.total as number
		ElMessage.success(res.success?.message)
	})
}
const big_auto_complete_in_exportDIY = (data: BigAutoCompletion) => {
	fuzzy_search.id = data.big_id
	fuzzy_search.mode = 'big'
	small_clear.value.clear_input()
}
const small_auto_complete_in_exportDIY = (data: SmallAutoCompletion) => {
	fuzzy_search.id = data.small_id as number
	fuzzy_search.mode = 'small'
	big_clear.value.clear_input()
}
const now_export_table_index = ref<number | undefined>() // 当前被选中展示的表格的下标

const add_new_small_id = (row: DIYContent) => {
	if (add_small_id.value === false) {
		ElMessage.warning('尚未选择表格，不可添加内容')
		return
	}
	// 在添加前进行校验，列表中的id不可重复
	for (let i of content_list.value) {
		if (i.id === row.id) {
			ElMessage.warning('您要添加的小类已经存在在列表中')
			return
		}
	}
	// 在第二个窗格处进行添加
	content_list.value.push(row)
	// 在id_list上进行添加
	export_list.value[now_export_table_index.value as number].id_list.push(row.id)
}

//---------------------------------------------------------------
// 表格2 查看导出表格内容 content_list
//---------------------------------------------------------------
const add_small_id = ref<boolean>(false)// 标志，若为true，则开放添加小类，否则一旦点击添加则报警
const content_list = ref<DIYContent[]>([])


// 这里逻辑有较大问题，
const delete_selected_small_id = (row: DIYContent) => {
	// 在content中删除元素
	content_list.value = content_list.value.filter(item => item.id !== row.id)
	export_list.value[now_export_table_index.value as number].id_list = export_list.value[now_export_table_index.value as number].id_list.filter(item => item !== row.id)
	// 在表一的content中删除元素
	export_list.value[now_export_table_index.value as number].content = export_list.value[now_export_table_index.value as number].content.filter(item => item.id !== row.id)
}


//---------------------------------------------------------------
// 表格1 查看所有可导出表格 export_list
//---------------------------------------------------------------
const export_list = ref<DIYFileDate[]>([])
// 点击按钮后在最右侧显示表格包含的小类
const show_content_list = (index: number, row: DIYFileDate) => {
	content_list.value = row.content
	add_small_id.value = true
	now_export_table_index.value = index
	area4.area2_name = row.name
}

// 将要返回的表格的id和名字填入区域4
const return_select_table_id = (row: DIYFileDate) => {
	area4.id = row.id
	area4.name = row.name
}


// 修改导出表格内容
const handleEdit = (row: DIYFileDate) => {
	dialogFormVisible.value = true
	add_revise.value = '修改表格'
	formInline.name = row.name
	formInline.id = row.id
	formInline.id_list = row.id_list
	dialogFormModel = 'modify'
}
// 添加一个导出表格的预设
const handleAdd = () => {
	dialogFormVisible.value = true
	add_revise.value = '添加表格'
	formInline.name = ''
	dialogFormModel = 'add'
}
// 刷新表格
const refresh = async () => {
	reqDIYCRUD({mode: 'read'}).then((result: DIYFileCRUDResponseData) => {
		export_list.value = result.read?.data as DIYFileDate[]
		ElMessage.success(result.success?.message)
	})
}


const form = ref<FormInstance>() // 弹出框的表单对象
let dialogFormModel: string = '' // 决定这个框到底是 修改框还是添加框
const dialogFormVisible = ref<boolean>(false) // 决定 修改/添加角色框 是否显示
const add_revise = ref<string>('') // 决定这个表单显示的名称是添加还是修改
// 表单内容
const formInline = reactive<{
	name: string,
	id_list: number[],
	id: number,
}>({
	name: '',
	id_list: [],
	id: 0,
})
// 表单字段验证
const rules = reactive<FormRules>({
	name: [{
		required: true,
		message: '必填项',
		type: 'string',
		max: 20,
		min: 1
	}],
})
// 添加表格和修改表格
const onSubmit = () => {
	// 这是组件要求的，要改这个可见状态
	dialogFormVisible.value = false
	form.value?.validate(async (validate) => {
		// 添加用户信息
		if (dialogFormModel === 'add') {
			if (validate) {
				const result: DIYFileCRUDResponseData = await reqDIYCRUD({
					mode: 'create',
					create: {
						name: formInline.name,
					}
				})
				ElMessage.success(result.success?.message)
			}
		} else {
			// 修改用户信息
			if (validate) {
				const result: DIYFileCRUDResponseData = await reqDIYCRUD({
					mode: 'update',
					update: {
						export_id: formInline.id,
						update_id_list: formInline.id_list,
						name: formInline.name,
					}
				})
				ElMessage.success(result.success?.message)
			}
		}
	})
}
// 删除表格
const handleDelete = (row: DIYFileDate) => {
	ElMessageBox.alert('确认删除该表格吗？', '确认', {
		confirmButtonText: '确认',
		callback: async (action: string) => {
			if (action === 'confirm') {
				const result: DIYFileCRUDResponseData = await reqDIYCRUD({
					mode: 'delete',
					delete: {
						delete_id: row.id,
					}
				})
				ElMessage.success(result.success?.message)
			}
		},
	})
}


//---------------------------------------------------------------
// 显示表格区域
//---------------------------------------------------------------
// 在第四区域显示表格
const return_table = async () => {
	if (area4.date_range === null) {
		ElMessage.warning('请选择导出日期')
		return
	}
	if (area4.id === '') {
		ElMessage.warning('请选择导出表格')
		return
	}
	const result: DIYReturnDataResponseData = await reqDIYTable({
		export_id: area4.id,
		date_start: area4.date_range[0],
		date_stop: area4.date_range[1],
		trend: area4.trend,
	})
	ElMessage.success(`${area4.name} 表返回成功`)
	DIY_data.value = result.data
}

// 在后端生成表格然后返回
const return_small_list_backhand = async () => {
	if (area4.date_range === null) {
		ElMessage.warning('请选择导出日期')
		return
	}
	if (area4.id === '') {
		ElMessage.warning('请选择导出表格')
		return
	}
	await req04Table({
		export_id: area4.id,
		date_start: area4.date_range[0],
		date_stop: area4.date_range[1],
		trend: area4.trend,
	})
	ElMessage.success(`${area4.name} 表返回成功`)
}

// 第四区域返回条件
const area4 = reactive<{
	trend: boolean
	date_range: [string, string] | null
	id: '' | number
	name: string
	area2_name: string
}>({
	trend: true,
	date_range: null,
	id: '',
	name: '',
	area2_name: '',
})

const DIY_data = ref() // 表格的ref
const table1_head_optional = reactive({
	actual_date_str: true,
	handle_name: true,
	big_name: true,
	small_name: true,
	no: true,
	model: true,
	units: true,
	change: true,
	unit_price: true,
	total: true,
	remarks: false,
})
const table1_head_show_visible = ref<boolean>() // 决定选择列的框是否显示
// 选择表格可以导出的列
const select_table4_col = () => {
	table1_head_show_visible.value = true
}
const select_table4_col_confirm = () => {
	table1_head_show_visible.value = false
}

</script>

<style scoped>

</style>